package com.leng.admin.config;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.google.common.collect.Maps;
import com.leng.common.constant.Constants;
import com.leng.common.constant.LoginErrorConstants;
import com.leng.common.core.entity.admin.LoginUser;
import com.leng.common.exception.CaptchaException;
import com.leng.common.exception.CaptchaExpireException;
import com.leng.common.exception.CustomException;
import com.leng.common.exception.UserPasswordNotMatchException;
import com.leng.common.redis.RedisCache;
import com.leng.common.utils.AddressUtils;
import com.leng.common.utils.IpUtils;
import com.leng.common.utils.MessageUtils;
import com.leng.common.utils.ServletUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 登录校验方法
 *
 * @author Community
 */
@Component
@Service
public class LoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AmqpTemplate amqpTemplate ;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {

        HashMap<String, Object> maps = Maps.newHashMap();
        HttpServletRequest request = ServletUtils.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        String address = AddressUtils.getRealAddressByIP(ip);
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        maps.put(LoginErrorConstants.LOGIN_IPADDR,ip) ;
        maps.put(LoginErrorConstants.LOGIN_LOCATION,address);
        maps.put(LoginErrorConstants.LOGIN_OS,os);
        maps.put(LoginErrorConstants.LOGIN_BROWSER,browser);
        maps.put(LoginErrorConstants.USER_NAME,username) ;
        maps.put(LoginErrorConstants.LOGIN_STATUS,Constants.LOGIN_FAIL) ;
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
//        if (captcha == null)
//        {
////          AsyncManager.me().execute(AgentAdminAsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
//            maps.put(LoginErrorConstants.LOGIN_MESSAGE,MessageUtils.message("user.jcaptcha.expire")) ;
//            amqpTemplate.convertAndSend(Constants.LOGIN_ASYNCHRONOUS,maps) ;
//            throw new CaptchaExpireException();
//        }
//        if (!code.equalsIgnoreCase(captcha))
//        {
////            AsyncManager.me().execute(AgentAdminAsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
//            maps.put(LoginErrorConstants.LOGIN_MESSAGE,MessageUtils.message("user.jcaptcha.error")) ;
//            amqpTemplate.convertAndSend(Constants.LOGIN_ASYNCHRONOUS,maps) ;
//            throw new CaptchaException();
//        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
//                AsyncManager.me().execute(AgentAdminAsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                maps.put(LoginErrorConstants.LOGIN_MESSAGE,MessageUtils.message("user.password.not.match")) ;
                amqpTemplate.convertAndSend(Constants.LOGIN_ASYNCHRONOUS,maps) ;
                throw new UserPasswordNotMatchException();
            }
            else
            {
//                AsyncManager.me().execute(AgentAdminAsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                maps.put(LoginErrorConstants.LOGIN_MESSAGE,e.getMessage()) ;
                amqpTemplate.convertAndSend(Constants.LOGIN_ASYNCHRONOUS,maps) ;
                throw new CustomException(e.getMessage());
            }
        }
//        AsyncManager.me().execute(AgentAdminAsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        maps.put(LoginErrorConstants.LOGIN_STATUS,Constants.LOGIN_SUCCESS) ;
        maps.put(LoginErrorConstants.LOGIN_MESSAGE,MessageUtils.message("user.login.success")) ;
        amqpTemplate.convertAndSend(Constants.LOGIN_ASYNCHRONOUS,maps) ;
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
